package com.why.controller;


import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.why.entity.News;
import com.why.service.NewsService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.List;

/**
 * 平台公告(News)表控制层
 *
 * @author makejava
 * @since 2023-05-12 20:16:02
 */
@RestController
@RequestMapping("/news")
@CrossOrigin
public class NewsController {
    /**
     * 服务对象
     */
    @Autowired
    private NewsService newsService;


    /**
     * 添加资讯
     *
     * @param news
     * @return
     */
    @PostMapping("/save")
    public String save(@RequestBody News news) {
        newsService.save(news);
        return "success";
    }


    /**
     * 分页查询
     *
     * @param page
     * @param pageSize
     * @param name
     * @return
     */
    @GetMapping("/page")
    public Page<News> page(int page, int pageSize, String name) {
        Page<News> pageInfo = new Page(page, pageSize);
        LambdaQueryWrapper<News> queryWrapper = new LambdaQueryWrapper<News>();
        queryWrapper.like(name != null, News::getTitle, name);
        queryWrapper.orderByDesc(News::getId);
        newsService.page(pageInfo, queryWrapper);
        return pageInfo;
    }

    /**
     * 获取校园资讯
     *
     * @return
     */
    @GetMapping("/getnews")
    public List getNews() {
        LambdaQueryWrapper<News> queryWrapper = new LambdaQueryWrapper<News>();
        //发布的资讯进行展示
        queryWrapper.eq(News::getStatus, 1);
        queryWrapper.select(News::getContent, News::getTitle);
        List list = newsService.list(queryWrapper);
        return list;
    }


    @PostMapping("/update")
    public String update(@RequestBody News news) {
        LambdaQueryWrapper<News> queryWrapper = new LambdaQueryWrapper<News>();
        queryWrapper.eq(News::getId, news.getId());
        newsService.update(news, queryWrapper);
        return "success";
    }

    @PostMapping("/delete")
    public String delete(@RequestBody News news) {
        System.out.println(news);
        newsService.removeById(news.getId());
        return "success";
    }

}

